//
//  CSBaseView.m
//  市场监管通
//
//  Created by 网新中研 on 16/4/8.
//  Copyright © 2016年 centralsoft. All rights reserved.
//

#import "CSBaseView.h"
#import "Common.h"

#import "CS_Development_EditFocusView.h"


@interface CSBaseView()

/**
 * 分割线
 */
@property (nonatomic, strong) UIView *seperatorLineView;

@property (nonatomic, strong) UIButton *developeButton;

/**
 * 卡片风格
 */
@property (nonatomic, strong) UIView *cardBackgroundView;

@end

@implementation CSBaseView

static NSMutableDictionary *_colorStringDic;
static NSMutableArray *_colorStringKeyList;



static UIImage *_preloadImage;

+(void)loadPreloadImage:(UIImage *)image{
    
    
    
    _preloadImage = image;
}

+(void)setApplicationColoredString:(NSString *)keyString color:(UIColor *)color{
    
    if (keyString == nil || [keyString isEqualToString:@""] || color == nil) {
        return;
    }
    
    if (_colorStringDic == nil) {
        _colorStringDic = [NSMutableDictionary new];
        _colorStringKeyList = [NSMutableArray new];
    }
    
    UIColor *colorBefore = [_colorStringDic objectForKey:keyString];
    
    if (colorBefore == nil) {
        
        [_colorStringDic setObject:color forKey:keyString];
        [_colorStringKeyList addObject:keyString];
        
    }
    
}

+(void)colorApplicationColoredString:(NSMutableAttributedString *)attributedString{
    
    for (int i = 0; i < _colorStringKeyList.count; i++) {
        
        NSString *keyString = [_colorStringKeyList objectAtIndex:i];
        UIColor *color = [_colorStringDic objectForKey:keyString];
        
        NSRange rangeOfString = [attributedString.string rangeOfString:keyString];
        [attributedString addAttribute:NSForegroundColorAttributeName value:color range:rangeOfString];
        
    }
}

/**
 * 清除应用制定关键字的变色处理
 */
+(void)clearApplicationColoredKey:(NSString *)keyString{
    
    if (keyString == nil || [keyString isEqualToString:@""]) {
        return;
    }
    
    [_colorStringDic removeObjectForKey:keyString];
    [_colorStringKeyList removeObject:keyString];
    
}

+(UIImage*)preloadImage{
    return _preloadImage;
}

-(instancetype)init{
    if (self = [super init]) {
        self.leftMargin = CELL_EDIT_RIGHT_MARGIN;
        self.rightMargin = CELL_EDIT_RIGHT_MARGIN;
    }
    return self;
}

#pragma mark --- Layout

-(void)setSeperateKey:(NSString *)seperateKey{
    if (![self isNullOrEmpty:seperateKey]) {
        self.seperateKeyString = seperateKey;
    }
}

/**
 * 添加分割线
 */
-(CGFloat)addSeperatorLine:(UIView *)superView primaryY:(CGFloat)primaryY{
    
    return primaryY;
    
    CGFloat localPrimaryY = primaryY;
    
    self.seperatorLineView.frame = CGRectMake(CELL_SEPERATOR_MARGIN_LEFT, localPrimaryY + 3, kWindowW - CELL_SEPERATOR_MARGIN_LEFT, CELL_SEPERATOR_LINE_HEIGHT);
    
    [superView addSubview:self.seperatorLineView];
    
    return localPrimaryY + 7;
    
}

-(CGFloat)layoutView:(UIView *)superView primaryY:(CGFloat)primaryY{
    
    if(self.isNecessary){//
        NSString *contentStr = [NSString stringWithFormat:@"*%@", self.descriptionLabel.text];
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:contentStr];
        //设置：在0-3个单位长度内的内容显示成红色
        [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 1)];
        self.descriptionLabel.attributedText = str;
    }
    
    self.backgroundColor = COLOR_PAGE_BACKGROUND;
    
    if (self.isDevelopmentMode) {
        self.developeButton.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
        [self addSubview:_developeButton];
    }
    
//    //卡片风格
//    self.cardBackgroundView.frame = CGRectMake(10, 0, self.frame.size.width - 20, self.frame.size.height);
//    [self insertSubview:self.cardBackgroundView atIndex:0];
//    
//    if (![self isCornerRadusRequired]) {
//        UIView *lineHideView = [[UIView alloc]init];
//        lineHideView.frame = CGRectMake(11, -3, self.frame.size.width - 22, 4);
//        lineHideView.backgroundColor = [UIColor whiteColor];
//        [self insertSubview:lineHideView atIndex:1];
//    }
    
    self.backgroundColor = [UIColor clearColor];
    
    self.isRefreshRequired = NO;
    
    return primaryY;
}

/**
 *  父视图
 *
 *  @param superView
 *
 *  @return 添加该视图后的Y坐标高度
 */
-(CGFloat)layoutViewForRefresh:(UIView *)superView primaryY:(CGFloat)primaryY{
    
    if (self.isRefreshRequired) {
        
        primaryY = [self layoutView:superView primaryY:primaryY];
        self.isRefreshRequired = NO;
        return primaryY;
        
    }else{
        self.frame = CGRectMake(self.frame.origin.x, primaryY, self.frame.size.width, self.frame.size.height);
        [superView addSubview:self];
        return primaryY + self.frame.size.height;
    }
    
}

-(void)refreshSelfAndAdjustContext{
    
    if (self.superview) {
        
        self.isRefreshRequired = YES;
        
        if ([self.superview isKindOfClass:[CSBaseView class]]) {//如果上级视图是CSBaseView形式的，则将刷新的权利交给上级CSBaseView视图，由它统一分配
            
            //刷新权利的移交
            self.isRefreshRequired = NO;
            ((CSBaseView *)self.superview).isRefreshRequired = YES;
            [(CSBaseView *)self.superview refreshSelfAndAdjustContext];
            
            return;
        }
        
        NSMutableArray *relativeYDistanceList = [NSMutableArray new];//相对于上一个的位置
        CGFloat previousY = 0.0;
        
        for (int i = 0; i < self.superview.subviews.count; i++) {
            
            UIView *subView = [self.superview.subviews objectAtIndex:i];
            
            CGFloat relativeDistance = subView.frame.origin.y - previousY;
            
            [relativeYDistanceList addObject:@(relativeDistance)];
            
            previousY = subView.frame.origin.y + subView.frame.size.height;
            
        }
        
        previousY = 0;
        
        NSArray *subViews = self.superview.subviews;
        UIView *superView = self.superview;
        REMOVE_SUBVIEWS(superView);
        
        //刷新并保持个视图之间的相对位置
        for (int i = 0; i < subViews.count; i++) {
            
            UIView *subView = [subViews objectAtIndex:i];
            
            CGFloat primaryY = previousY + [[relativeYDistanceList objectAtIndex:i] floatValue];
            
            //如果不是CSBaseView,就处理相对位子
            if ([subView isKindOfClass:[CSBaseView class]]){
                
                previousY = [((CSBaseView *)subView) layoutViewForRefresh:superView primaryY:primaryY];
                
            }else{
                
                subView.frame = CGRectMake(subView.frame.origin.x, previousY, subView.frame.size.width, subView.frame.size.height);
                previousY = subView.frame.origin.y + subView.frame.size.height;
                
                [superView addSubview:subView];
                
            }
            
        }
        
        //如果上级视图是滚动视图,则更新其大小
        if ([self.superview isKindOfClass:[UIScrollView class]]) {
            
            UIScrollView *scrollView = (UIScrollView *)self.superview;
            scrollView.contentSize = CGSizeMake(0, previousY);
            
        }
        
        self.isRefreshRequired = NO;
    }
}

-(BOOL)isCornerRadusRequired{
    return NO;
}

-(UIView *)cardBackgroundView{
    if (_cardBackgroundView == nil) {
        _cardBackgroundView = [[UIView alloc]init];
//        _cardBackgroundView.layer.shadowColor = [UIColor blackColor].CGColor;
//        _cardBackgroundView.layer.shadowOffset = CGSizeMake(0, 0.2);
//        _cardBackgroundView.layer.shadowOpacity = 0.3;
        
        if ([self isCornerRadusRequired]) {
            _cardBackgroundView.layer.cornerRadius = 10.0;
            _cardBackgroundView.layer.masksToBounds = YES;
        }
        _cardBackgroundView.layer.borderColor = [UIColor colorFromHexCode:@"dadde4"].CGColor;
//        _cardBackgroundView.layer.borderColor = COLOR_THEME.CGColor;
        _cardBackgroundView.layer.borderWidth = 0.5;
        self.cardBackgroundView.backgroundColor = [UIColor whiteColor];
    }
    return _cardBackgroundView;
}

-(void)editClick{
    
    if (self.pageElementModel) {
        
        //编辑框绑定视图
        [[CS_Development_EditFocusView sharedInstance] bindView:self.pageElementModel];
    }
    
}
#pragma mark --- Value process

-(void)reset{
    
}

#pragma mark --- lazy loading

-(UIButton *)developeButton{
    if (_developeButton == nil) {
        _developeButton = [UIButton new];
        [_developeButton addTarget:self action:@selector(editClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _developeButton;
}


#pragma mark --- Pop show

/**
 * 弹出显示
 */
-(void)popShow:(UIViewController *)superViewController{
    
    //Show in popup
    KLCPopupLayout layout = KLCPopupLayoutMake(KLCPopupHorizontalLayoutCenter,
                                               KLCPopupVerticalLayoutCenter);
    
    KLCPopup* popup = [KLCPopup popupWithContentView:self
                                            showType:KLCPopupShowTypeGrowIn
                                         dismissType:KLCPopupDismissTypeShrinkOut
                                            maskType:KLCPopupMaskTypeDimmed
                            dismissOnBackgroundTouch:YES
                               dismissOnContentTouch:NO];
    self.superKLCPopup = popup;
    self.layer.cornerRadius = 5;
//    self.layer.borderWidth = 1;
//    UIColor *borderColor = COLOR_DIMGGREY;
//    self.layer.borderColor = borderColor.CGColor;
//    self.layer.masksToBounds = YES;
    self.layer.shadowOpacity = 0.3;
    self.layer.shadowColor = [UIColor blackColor].CGColor;
//    self.layer.shadowColor = COLOR_THEME.CGColor;
    self.layer.shadowOffset = CGSizeMake(0, 1);
    
    [popup showWithLayout:layout];
}

/**
 * 弹出显示
 */
-(void)popShow{
    
    //Show in popup
    KLCPopupLayout layout = KLCPopupLayoutMake(KLCPopupHorizontalLayoutCenter,
                                               KLCPopupVerticalLayoutCenter);
    
    KLCPopup* popup = [KLCPopup popupWithContentView:self
                                            showType:KLCPopupShowTypeGrowIn
                                         dismissType:KLCPopupDismissTypeShrinkOut
                                            maskType:KLCPopupMaskTypeDimmed
                            dismissOnBackgroundTouch:YES
                               dismissOnContentTouch:NO];
    self.superKLCPopup = popup;
    self.layer.cornerRadius = 5;
    self.layer.shadowOpacity = 0.3;
    self.layer.shadowColor = [UIColor blackColor].CGColor;
    self.layer.shadowOffset = CGSizeMake(0, 1);
    
    [popup showWithLayout:layout];
}

/**
 * 从底部向上弹出显示
 */
-(void)bottomShow{
    
    //Show in popup
    KLCPopupLayout layout = KLCPopupLayoutMake(KLCPopupHorizontalLayoutCenter,
                                               KLCPopupVerticalLayoutBottom);
    
    KLCPopup* popup = [KLCPopup popupWithContentView:self
                                            showType:KLCPopupShowTypeSlideInFromBottom
                                         dismissType:KLCPopupDismissTypeSlideOutToBottom
                                            maskType:KLCPopupMaskTypeDimmed
                            dismissOnBackgroundTouch:YES
                               dismissOnContentTouch:NO];
    self.superKLCPopup = popup;
    self.layer.cornerRadius = 5;
    self.layer.shadowOpacity = 0.3;
    self.layer.shadowColor = [UIColor blackColor].CGColor;
    self.layer.shadowOffset = CGSizeMake(0, 1);
    
    [popup showWithLayout:layout];
    
}

-(void)topShow{
    
    //Show in popup
    KLCPopupLayout layout = KLCPopupLayoutMake(KLCPopupHorizontalLayoutCenter,
                                               KLCPopupVerticalLayoutTop);
    
    KLCPopup* popup = [KLCPopup popupWithContentView:self
                                            showType:KLCPopupShowTypeSlideInFromTop
                                         dismissType:KLCPopupDismissTypeSlideOutToTop
                                            maskType:KLCPopupMaskTypeDimmed
                            dismissOnBackgroundTouch:YES
                               dismissOnContentTouch:NO];
    self.superKLCPopup = popup;
    self.layer.cornerRadius = 5;
    self.layer.shadowOpacity = 0.3;
    self.layer.shadowColor = [UIColor blackColor].CGColor;
    self.layer.shadowOffset = CGSizeMake(0, 1);
    
    [popup showWithLayout:layout];
    
    
}

-(NSInteger)viewType{
    return 0;
}

#pragma mark --- Lazy loading

- (UILabel *)titleLabel {
    if(_titleLabel == nil) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.font = [UIFont systemFontOfSize:FONT_SIZE_REM];
        _titleLabel.textColor = COLOR_TEXT_3;
        _titleLabel.textAlignment = NSTextAlignmentRight;
        _titleLabel.numberOfLines = 0;
    }
    return _titleLabel;
}

- (UILabel *)descriptionLabel {
    if(_descriptionLabel == nil) {
        _descriptionLabel = [[UILabel alloc] init];
        _descriptionLabel.font = [UIFont systemFontOfSize:FONT_SIZE_REM];
        _descriptionLabel.textColor = [UIColor blackColor];
        _descriptionLabel.textAlignment = NSTextAlignmentRight;
        _descriptionLabel.numberOfLines = 0;
    }
    return _descriptionLabel;
}

- (UIView *)seperatorLineView {
    if(_seperatorLineView == nil) {
        _seperatorLineView = [[UIView alloc] init];
        STYLE_SEPERATOR_LINE(_seperatorLineView);
    }
    return _seperatorLineView;
}

/**
 * 隐藏键盘
 */
-(void)hideKeyboard{
    
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.pageElementModel.pageEngine hideKeyboard];
}


-(void)showPage{
    [self.pageElementModel.pageEngine showPage:self.pageElementModel];
}

-(UIImageView *)downArrowImageView{
    if (_downArrowImageView == nil) {
        UIImage *arrow_more_image = [CSPageEngine getImageWithKey:KEY_ICON_ARROW_MORE];
        _downArrowImageView = [[UIImageView alloc]initWithImage:arrow_more_image];
    }
    return _downArrowImageView;
}


@end
